%Generate the syms matrix L.
%
%Generate syms matrix L, where n is the degree of matrix A and m is the
%degree of A and m is the degree of the state vector x in homogeneous form.
%
%Prototype: [L] = generateSymsL(n, m, hState, d)
%
%Input:     n - Degree of A
%           m - Degree of the state vector x in homogeneous form
%           hState - Homogeneous state vector
%           d - Dimension of homogeneous state vector hState
%
%Output:    L - Syms matrix L

function [ L ] = generateSymsL( n, m, hState, d )

syms x;
for i=1:n
    x(i) = ['x_' int2str(i)];
end

%Row Vector hState without using ' because of conj() function
for i=1:d
    hStateRow(i) = hState(i);
end

%Build the paramtric and symmetric matrix L.
%If degree of matrix L is dxd, the number of parameters is defined as:
%numOfParam = d + (d-1) + (d-2) + ... + 1
numOfParam = 0;
for i=1:d
    numOfParam = numOfParam + i;
end

syms alfa;

for i=1:numOfParam
    alfa(i) = sdpvar(1);
end

alfa_index = 1;
for i=1:d
    for j=1:d
        if j>=i
            L(i,j)=alfa(alfa_index);
            alfa_index = alfa_index + 1;
        else
            L(i,j)=L(j,i);
        end
    end
end

system=hStateRow*L*hState;

k=1;
for i=1:d
    for j=i:d
        divisors(k) = hState(i)*hState(j);
        k=k+1;
    end
end

for i=1:length(divisors)
    chr = char(expand(system/divisors(i)));
    equation{i} = generateCoefficientEquationFromString(chr);
end

equation = clearEquation(equation);

warning off
for i=1:length(equation)
    actualEquation = equation{i};
    found = false;
    j=1;
    while found == false && j <= length(alfa)
        actualVariable = alfa(j);
        if actualVariable == 0
            actualVariable = NaN;
        end
        if strfind(equation{i},char(actualVariable))
            alfa(j) = solve(actualEquation,actualVariable);
            found = true;
        else
            j = j+1;
        end
    end
end
warning on

alfa_index = 1;
for i=1:d
    for j=1:d
        if j>=i
            L(i,j)=strrep(char(alfa(alfa_index)), ' ', '');
            alfa_index = alfa_index + 1;
        else
            L(i,j)=L(j,i);
        end
    end
end

return;

end
